package com.util;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

public class RedisClient {
    private static RedisClient redisClient;
    private  static ShardedJedisPool shardedJedisPool;//切片连接池


    private RedisClient(){
        ArrayList<String> list =  new ArrayList<String>();
        list.add("180.76.148.76:6379");
        createJedisPool(null,list);
        // initialShardedPool();
        //shardedJedis = shardedJedisPool.getResource();
        /*jedis = jedisPool.getResource();

        jedis.auth("wzc4639658");*/
    }


    public static synchronized ShardedJedis getRedisClient() {

        if (redisClient == null) {
            redisClient = new RedisClient();
            System.out.println("----Jedis---");
        }
        return  shardedJedisPool.getResource();
    }


    /**
     * 建立连接池 真实环境，一般把配置参数缺抽取出来。
     */
    private static void createJedisPool(String password, List<String> hosts) {
        // 生成多机连接信息列表
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        for (String hostInfo : hosts) {
            String[] hostArr = hostInfo.split(":");
            JedisShardInfo jsi = new JedisShardInfo(hostArr[0], Integer.parseInt(hostArr[1]));
            if(password!=null) {
                jsi.setPassword(password);
            }
            shards.add(jsi);
        }
        //shards.add( new JedisShardInfo("192.168.56.102", 6379) );

        // 生成连接池配置信息
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(20);
        config.setMaxTotal(20);
        config.setMaxWaitMillis(23);

        // 在应用初始化的时候生成连接池
        shardedJedisPool = new ShardedJedisPool(config, shards);

    }


    /* *//**
     * 初始化切片池 
     *//*
    private void initialShardedPool() 
    { 
        // 池基本配置 
        JedisPoolConfig config = new JedisPoolConfig();
        //config.setMaxActive(20);
        config.setMaxIdle(5);
        //config.setMaxWait(1000l);
        config.setTestOnBorrow(false); 
        // slave链接 
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); 
        shards.add(new JedisShardInfo("180.76.148.76", 6379, null));

        // 构造池 
        shardedJedisPool = new ShardedJedisPool(config, shards); 
    }*/

    public static void main(String[] args) {


       RedisClient redisClient = new RedisClient();
        System.out.println(redisClient.getRedisClient().set("33","33"));
        System.out.println(redisClient.getRedisClient().set("33","33"));
        System.out.println(redisClient.getRedisClient().set("33","33"));

    }



}